import { ElMessageBox } from 'element-plus'
import {
  useAppStore, usePermissionStore, useUserStore, AppStorePropsType, PermissionStorePropsType, UserStorePropsType,
  useTagsViewStore, TagsViewStorePropsType, useDictStore, DictStorePropsType
} from '@fssc/admin';
import { findAdminByToken, loginOut } from '../api/passport-auth';
import type { FsscUtilOption } from '../util';
import { merge } from 'lodash-es'

let piniaStore = null;

export const useAppStoreWithOut = () : AppStorePropsType => useAppStore(piniaStore);

export const usePermissionStoreWithOut = () : PermissionStorePropsType => usePermissionStore(piniaStore);

export const useUserStoreWithOut = () : UserStorePropsType => {
  const userStore = useUserStore(piniaStore);
  return userStore;
};

export const useTagsViewStoreWithOut = () : TagsViewStorePropsType => useTagsViewStore(piniaStore);

export const useDictStoreWithOut = () : DictStorePropsType => useDictStore(piniaStore);


export type InitStoreOption = {
  store: {
    piniaStore: any,
  },
  // 登录过后请求到用户信息时需要初始化的动作
  afterLogin?: (store: any) => Promise<any>,
  // 树池化appState配置
  appState: any
}

// 初始化store
export function initStore(config: InitStoreOption) {
  piniaStore = config.store.piniaStore;

  //  初始化应用信息
  const appStore = useAppStoreWithOut()

  merge(appStore, config.appState)

  // user store 修改
  piniaStore.use((context) => {
    const { store } = context;
    if (store.$id === 'user') {
      store.requestUserInfo = async () => {
        const userInfo = await findAdminByToken(appStore.projectInfo.key);
        store.setUserInfo(userInfo);

        if(config.afterLogin) {
          await config.afterLogin(piniaStore);
        }
      };

      store.requestLogout = async (showConfirm?: boolean) => {
        if (showConfirm) {
          await ElMessageBox.confirm('确定要退出登录吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
        }
        try {
          const data = await loginOut()
          await findAdminByToken(appStore.projectInfo.key, { noShowError: true});
        } catch (err) {
          console.log(err);
        }
      };
    }
  });
}

/**
 * @description: 表格字典格式化，需保证数据字典提前加入到store中
 * @param {*} row
 * @param {*} column
 * @param {*} cellValue
 * @param {*} index
 * @return {*}
 */
function dictFormatter(row: any, column: any, cellValue: any, index: number) {
  const dictStore = useDictStoreWithOut()
  // 配置的时候配类型
  return dictStore.valueToLabelSync(cellValue, column.type)
}

export {
  useAppStore,
  usePermissionStore,
  useUserStore,
  useDictStore,
  useTagsViewStore,
  dictFormatter
};
